#!/usr/bin/python
# -*- coding: utf-8 -*-
#Create Time : 2006 2006-6-6 23:23:38
#Create By User : 

from dpkt import ethernet, arp
import dpkt
import socket
import string
import struct
import sys
from time import sleep

NETWORKER = ( 
             ( 'eth1', '00:07:E9:63:4E:1B', '192.168.2.7', '192.168.2.' ),\
             )

debugToggle = 0
def show_debug( *values ):
    if debugToggle == 0: return
    print >> sys.stderr, "", 
    for v in values: print >> sys.stderr, v, 
    print >> sys.stderr, '.'

# this should be somewhere is dpkt ? 
ETH_ADDR_BROADCAST = '\xff\xff\xff\xff\xff\xff'
ETH_ADDR_UNSPEC = '\x00\x00\x00\x00\x00\x00'

def eth_ntoa( buffer ):
    # Convert binary data into a string.
    macaddr = ''
    for intval in struct.unpack( 'BBBBBB', buffer ):
        if intval > 15:
            replacestr = '0x'
        else:
            replacestr = 'x'
        macaddr = ''.join( [macaddr, hex( intval ).replace( replacestr, '' )] )
    return macaddr

def eth_aton( buffer ):
    addr =''
    temp = string.split( buffer, ':' )
    buffer = string.join( temp, '' )
    # Split up the hex values and pack.
    for i in range( 0, len( buffer ), 2 ):
        addr = ''.join( [addr, struct.pack( 'B', int( buffer[i: i + 2], 16 ) )], )
    return addr

def buildArp2( self_mac_addr, from_ip_addr, to_ip_addr ):
    arp_p = arp.ARP()
    arp_p.sha = eth_aton( self_mac_addr )          # sender hardware addr
    arp_p.spa = socket.inet_aton( from_ip_addr ) # sender ip addr
    arp_p.tha = ETH_ADDR_BROADCAST        # dest hardware addr 
    arp_p.tpa = socket.inet_aton( to_ip_addr ) # ip addr of request
    #arp_p.op = arp.ARP_OP_REQUEST # arp request
    arp_p.op = arp.ARP_OP_REPLY # arp replay

    packet = ethernet.Ethernet()
    packet.src = eth_aton( self_mac_addr )
    packet.dst = ETH_ADDR_BROADCAST
    packet.data = arp_p
    packet.type = ethernet.ETH_TYPE_ARP

    show_debug( dpkt.hexdump( str( packet ) ) )

    return packet

    
def main_loop():

    while 1:
        for x in NETWORKER:
            self_interface, self_mac_address, self_ipaddress, to_network = x
            s = socket.socket( socket.PF_PACKET, socket.SOCK_RAW )
            s.bind( ( self_interface, ethernet.ETH_TYPE_ARP ) )
            for i in range( 1, 255 ):
                to_ip = to_network+str( i )
                a_packet = buildArp2( self_mac_address, self_ipaddress, to_ip )
                show_debug( 'Sender Interfacer => %s' % self_interface )
                show_debug( 'Sender MAC Address => %s' % self_mac_address )
                show_debug( 'Sender IP Address => %s' % self_ipaddress )
                show_debug( 'To IP Address => %s' % to_ip )
                s.send( str( a_packet ) )
                sleep(.05)
            s.close()

if __name__ == '__main__':
    main_loop()